package com.atguigu.gmall.order.controller;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.product.client.ProductFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Ordering;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;


/**
 * @author atguigu-mqx
 */
@RestController
@RequestMapping("api/order")
public class OrderApiController {

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private CartFeignClient cartFeignClient;

    @Autowired
    private OrderService orderService;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;


    //  api/order/auth/trade    网关中设置了访问这个路径必须登录！
    @GetMapping("auth/trade")
    public Result authTrade(HttpServletRequest request){
        HashMap<String, Object> hashMap = new HashMap<>();
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //  获取送货地址列表：
        List<UserAddress> userAddressList = userFeignClient.findUserAddressListByUserId(userId);

        //  获取送货清单：
        List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(userId);
        //  循环遍历给订单明细赋值！
        //  计算件数：
        AtomicInteger totalNum = new AtomicInteger();
        List<OrderDetail> orderDetailList = cartCheckedList.stream().map(cartInfo -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setSkuId(cartInfo.getSkuId());
            orderDetail.setSkuName(cartInfo.getSkuName());
            orderDetail.setImgUrl(cartInfo.getImgUrl());
            orderDetail.setSkuNum(cartInfo.getSkuNum());
            orderDetail.setOrderPrice(cartInfo.getSkuPrice());
            totalNum.addAndGet(cartInfo.getSkuNum());
            return orderDetail;
        }).collect(Collectors.toList());

        //  计算总价格：
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderDetailList(orderDetailList);
        orderInfo.sumTotalAmount();

        //  存储数据：
        hashMap.put("userAddressList",userAddressList);
        //  订单业务需要换---> 缓存没有优惠券的页面！
        hashMap.put("detailArrayList",orderDetailList);
        //  两种：一种：计算集合的长度  集合长度 ：size(); 数组长度 length; 字符串：length(); 文件长度：length();
        //  一种：计算每个商品的skuNum
//        hashMap.put("totalNum",orderDetailList.size());
        hashMap.put("totalNum",totalNum);
        hashMap.put("totalAmount",orderInfo.getTotalAmount());
        //  保存一个流水号：
        hashMap.put("tradeNo",orderService.getTradeNo(userId));
        //        List<OrderDetail> orderDetails = new ArrayList<>();
        //        for (CartInfo cartInfo : cartCheckedList) {
        //            OrderDetail orderDetail = new OrderDetail();
        //            orderDetail.setSkuId(cartInfo.getSkuId());
        //            orderDetail.setSkuName(cartInfo.getSkuName());
        //            orderDetail.setImgUrl(cartInfo.getImgUrl());
        //            orderDetail.setSkuNum(cartInfo.getSkuNum());
        //            orderDetail.setOrderPrice(cartInfo.getSkuPrice());
        //            orderDetails.add(orderDetail);
        //        }
        //        cartCheckedList.stream().forEach(cartInfo -> {
        //            OrderDetail orderDetail = new OrderDetail();
        //            orderDetail.setSkuId(cartInfo.getSkuId());
        //            orderDetail.setSkuName(cartInfo.getSkuName());
        //            orderDetail.setImgUrl(cartInfo.getImgUrl());
        //            orderDetail.setSkuNum(cartInfo.getSkuNum());
        //            orderDetail.setOrderPrice(cartInfo.getSkuPrice());
        //            orderDetails.add(orderDetail);
        //        });


        //  返回
        return Result.ok(hashMap);
    }

    //  提交订单：http://api.gmall.com/api/order/auth/submitOrder?tradeNo=null
    //  前端传递的json ，后端需要使用java 对象接收！
    @PostMapping("auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo,HttpServletRequest request){
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //  获取到页面的流水号
        String tradeNo = request.getParameter("tradeNo");
        //  调用比较方法
        Boolean result = orderService.checkTradeNo(tradeNo, userId);
        if (!result){
            return Result.fail().message("不能回退无刷新重复提交订单！");
        }
        //  删除缓存的流水号！
        orderService.delTradeNo(userId);

        //  声明一个异步编排集合
        List<String> errorList = new ArrayList<>();
        List<CompletableFuture> futureList = new ArrayList<>();
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        if (!CollectionUtils.isEmpty(orderDetailList)){
            //  循环遍历当前的订单明细
            for (OrderDetail orderDetail : orderDetailList) {
                //  验证库存
                CompletableFuture<Void> stockCompletableFuture = CompletableFuture.runAsync(() -> {
                    Boolean res = orderService.checkStock(orderDetail.getSkuId(), orderDetail.getSkuNum());
                    //  校验库存！
                    if (!res) {
                        errorList.add(orderDetail.getSkuName() + "没有足够的库存！");
                    }
                }, threadPoolExecutor);
                //  将这个对象添加到集合！
                futureList.add(stockCompletableFuture);
                //  验证价格
                CompletableFuture<Void> priceCompletableFuture = CompletableFuture.runAsync(() -> {
                    //  校验价格：
                    BigDecimal orderPrice = orderDetail.getOrderPrice();
                    //  实时价格：
                    BigDecimal skuPrice = this.productFeignClient.getSkuPrice(orderDetail.getSkuId());
                    if (orderPrice.compareTo(skuPrice) != 0) {
                        //  设置最新的价格
                        List<CartInfo> cartCheckedList = this.cartFeignClient.getCartCheckedList(userId);
                        //  写入缓存：
                        cartCheckedList.forEach(cartInfo -> {
                            this.redisTemplate.opsForHash().put(RedisConst.USER_KEY_PREFIX + userId + RedisConst.USER_CART_KEY_SUFFIX, cartInfo.getSkuId().toString(), cartInfo);
                        });
                        errorList.add(orderDetail.getSkuName() + "价格有变动！");
                    }
                },threadPoolExecutor);
                //  将这个对象添加到集合！
                futureList.add(priceCompletableFuture);
            }
        }

        //  有个任务组合
        CompletableFuture.allOf(futureList.toArray(new CompletableFuture[futureList.size()])).join();
        //  判断是否有错误：
        if (errorList.size()>0){
            return Result.fail().message(StringUtils.join(errorList,","));
        }
        orderInfo.setUserId(Long.parseLong(userId));
        //  调用服务层方法
        Long orderId = orderService.saveOrderInfo(orderInfo);
        //  默认返回
        return Result.ok(orderId);
    }

    //  查看我的订单
    @GetMapping("auth/{page}/{limit}")
    public Result orderList(@PathVariable Long page,
                            @PathVariable Long limit,
                            HttpServletRequest request){
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        Page<OrderInfo> orderInfoPage = new Page<>(page,limit);

        //  获取到数据
        IPage<OrderInfo> infoIPage = orderService.getPage(orderInfoPage, userId);

        //  返回
        return Result.ok(infoIPage);

    }

    //  根据订单Id 来获取orderInfo
    @GetMapping("inner/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable Long orderId){
        //  调用服务层方法
        return this.orderService.getOrderInfo(orderId);
    }


    //  拆单控制器： http://localhost:8204/api/order/orderSplit
    //  http://order.gmall.com/orderSplit?orderId=xxx&wareSkuMap=xxx
    @PostMapping("orderSplit")
    public String orderSplit(HttpServletRequest request){
        String orderId = request.getParameter("orderId");
        String wareSkuMap = request.getParameter("wareSkuMap");

        //  调用服务层方法进行拆单：
        List<OrderInfo> orderInfoList = orderService.orderSplit(orderId,wareSkuMap);
        //  创建一个集合
        List<Map> maps = new ArrayList<>();

        //  循环遍历
        for (OrderInfo orderInfo : orderInfoList) {
            //  将orderInfo 转换为Map
            Map map = this.orderService.initWare(orderInfo);
            maps.add(map);
        }
        //  返回数据
        return JSON.toJSONString(maps);
    }

    //  更新订单评论
    @ApiOperation("更新订单评论状态")
    @GetMapping("inner/updateCommnetStatus/{orderId}")
    public Boolean updateCommnetStatus(@PathVariable(value = "orderId") Long orderId){
        orderService.updateCommnetStatus(orderId);
        return true;
    }

    //  封装一个秒杀的订单的数据接口：
    @PostMapping("inner/seckill/submitOrder")
    public Long seckillSubmitOrder(@RequestBody OrderInfo orderInfo){
        //  远程调用数据
        Long orderId = orderService.saveOrderInfo(orderInfo);
        //  返回订单Id 是为了给支付使用！
        return orderId;
    }


}
